<?php

class FireFeed_Feed_Consumer 
{
	/**
	 * Number of seconds to be elapsed before a new update well be done
	 */
	const UPDATE_INTERVAL = 3600;
	
	/**
	 * Get information of a feed channel from a given url
	 * 
	 * @param String $feedurl
	 * @return Model_Entity_Feed
	 */
    public static function getFeedInfo($feedurl)
    {
    	$feed = new Model_Entity_Feed();
    	
    	$channel = Zend_Feed_Reader::import($feedurl);
    	
    	$feed->setName($channel->getTitle());
        $feed->setUrl($channel->getLink());
        $feed->setDescription($channel->getDescription());
        
        return $feed;
    }
    
    /**
     * Get feed news from a given url
     * 
     * @param Model_Entity_Feed $feed
     * @param boolean $force optional
     * @return array of Model_Entity_News
     */
    public static function consumeFeed(Model_Entity_Feed $feed, $force = false)
    {
        $elapsed = time() - strtotime($feed->getLastSync());
        $upgradeNeeded = ($elapsed >= self::UPDATE_INTERVAL) ? true : false;
        
        $result = array();
        if ($upgradeNeeded || $force) {
	    	$channel = Zend_Feed_Reader::import($feed->getUrl());
		    foreach ($channel as $entry) {
		    	$news = new Model_Entity_News();
		    	
		    	$news->setTitle($entry->getTitle());
		    	$news->setDescription($entry->getDescription());
		    	$date = date('Y-m-d H:i:s', 
		    	             $entry->getDateCreated()->get(Zend_Date::TIMESTAMP));
		    	$news->setPubDate($date);
		    	$news->setUrl($entry->getLink());
		    	$news->setBody($entry->getContent());
		    	$news->setFeed($feed);
		    	
		    	$result[] = $news;
	        }
        }
        return $result;
    }
}
